package com.shanghai.tcp_client;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.shanghai.tcp_client.Utils.ByteUtils;
import com.shanghai.tcp_client.Utils.CRC16;
import com.shanghai.tcp_client.Utils.MyArrayUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    OutputStream outputStream;
    InputStream inputStream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

Button button=(Button)findViewById(R.id.start);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket=new Socket("192.168.1.1",502);
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();
                } catch (IOException e) {
                    e.printStackTrace();

                    Log.e("error",""+e.toString());
                }

                if (inputStream!=null){
                    SendThread sendThread=new SendThread();
                    sendThread.start();
                }
            }
        }).start();

    }
});




    }



     class SendThread extends Thread{
         @Override
         public void run() {
             super.run();
while (true){
             try {
                 outputStream.write(new byte[]{0x07,0x03,0,0,0,0x58,0x44,0x56});
             } catch (IOException e) {
                 e.printStackTrace();
             }
             try {
                 Thread.sleep(300);

                 readData(7);
                 Thread.sleep(300);




             } catch (InterruptedException e) {
                 e.printStackTrace();
             }

         }
     }}


    synchronized public boolean readData(int deviceID) {
        if (deviceID==7) {
            Log.e("","");
        }
        boolean isCommunicateSucceed =false;
        int length =181;
        int size = 0;
        byte[] receiveData = new byte[length];
        boolean isConcat = false;
        boolean isHead = false;
        byte[] buf = new byte[181];
        if (inputStream == null)
            return false;
        try {
            if (inputStream.available() != 0) {
                size = inputStream.read(buf);
                Log.e("comc_modbus","读数据1");
            }
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        Log.e("comc_modbus","读数据2");

//        Log.e("thread", "执行了没" + size);
        if (size > 0) {
            byte[] dest = new byte[size];
            System.arraycopy(buf, 0, dest, 0, size);
            // TODO: 2017/8/16 说明tempByte是数据包第一帧部分数据
            if ((dest[0] >= 1 && dest[0] <= 8) && (dest[1] == 3)) {//    java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
                receiveData = dest;
                isHead = true;
                isConcat = true;
            } else {
                isHead = false;
            }
            if (isConcat) {
                if (isHead) {
                    isHead = false;
                } else {
                    receiveData = ByteUtils.concat(receiveData, dest);
                }
            }
            Log.e("收到数据--", "" + MyArrayUtils.byteArrayToHexStr(receiveData));
//            Log.e("收到数据--", "" + receiveData.length+"---"+length);
            // TODO: 2017/8/16 0016 未校验数据是否正确
            if (receiveData.length == length) {
                if (0 < receiveData[0] && receiveData[0] < 9) {

                    if (CRC16.checkCRC16_bytes(receiveData)){
                        Log.e("crc","收到数据crc正确");
                        //接收到的数据
                        Log.d("收到数据0", "" + MyArrayUtils.byteArrayToHexStr(receiveData));
//                        receiveCommuntcateData_Modbus(deviceID, ArrayUtils.subarray(receiveData, 3, receiveData.length - 2));
//                    byte[] bytes=ArrayUtils.subarray(receiveData, 3, receiveData.length - 2);
//                    Log.d("收到数据1截取后：", "" + bytes.length);
//                    Log.d("收到数据1", "" + MyArrayUtils.byteArrayToHexStr(bytes));
//                    Log.e("","co");
                        isCommunicateSucceed=true;
                    }else {
                        Log.e("crc","收到数据crc错误");
                    }
                }
                receiveData = new byte[length];
            }
        }
        return isCommunicateSucceed;
    }

}
